import React, { useEffect, useState } from "react";
import {
  Form,
  Input,
  Button,
  DatePicker,
  Table,
  message,
  Upload,
  Modal,
  Select,
  InputNumber,
} from "antd";
import { UploadOutlined, SearchOutlined } from "@ant-design/icons";
import * as XLSX from "xlsx";
import moment from "moment";
import UploadModal from "../../components/UploadModal";
import {
  getBooksByPage,
  saveBookByForm,
  searchBookByName,
  updateBookFileUrlById,
  updateBookStatusById,
  updateBookTypeById,
} from "../../api/book";
import { uploadExcelFile } from "../../http/request";

const { Item } = Form;
const { Search } = Input;
const { Option } = Select;

const Creat = () => {
  const [form] = Form.useForm();
  const [formClassfiy] = Form.useForm();
  const [books, setBooks] = useState<any[]>([]);
  const [pageContent, setPageContent] = useState<any>({});
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [showClassfiy, setShowClassfiy] = useState(false);
  const [selectedBook, setSelectedBook] = useState<any>(null);
  const [categories, setCategories] = useState<any[]>([
    { key: "1", name: "社会科学" },
    { key: "2", name: "自然科学" },
  ]);
  const [showUpload, setShowUpload] = useState(false);
  const [showPdfUpload, setShowPdfUpload] = useState(false);
  const [currentPage, setCurrentPage] = useState(1); // 添加

  const columns = [
    { title: "书名", dataIndex: "name", key: "name" },
    { title: "作者", dataIndex: "author", key: "author" },
    { title: "ISBN", dataIndex: "isbn", key: "isbn" },
    { title: "出版日期", dataIndex: "publishDate", key: "publishDate" },
    {
      title: "分类",
      dataIndex: "category",
      key: "typeId",
      render: (text: any, record: any) =>
        categories.find((item) => item.key == record.typeId)?.name,
    },
    {
      title: "PDF 文件",
      dataIndex: "fileUrl",
      key: "fileUrl",
      render: (text: any, record: any) =>
        record.fileUrl ? (
          <a href={record.fileUrl} target="_blank" rel="noopener noreferrer">
            阅读
          </a>
        ) : (
          "未上传"
        ),
    },
    {
      title: "操作",
      key: "action",
      render: (text: any, record: any) => (
        <>
          <Button
            disabled={record.status == 1}
            onClick={() => {
              setSelectedBook(record);
              setShowClassfiy(true);
            }}
            style={{ marginRight: 8 }}
          >
            修改分类
          </Button>
          <Button
            type="primary"
            onClick={() => handleShelf(record)}
            disabled={record.status == 1}
            style={{ marginRight: 8 }}
          >
            {record.status == 1 ? "已上架" : "上架"}
          </Button>
          <Button
            type="default"
            onClick={() => handleUnshelf(record)}
            disabled={record.status == 0}
            style={{ marginRight: 8 }}
          >
            取消上架
          </Button>

          <Upload
            beforeUpload={(file) => handlePdfUpload(file, record)}
            showUploadList={false}
            accept=".pdf"
          >
            <Button icon={<UploadOutlined />}>
              {record?.fileUrl ? "重新上传" : "上传PDF"}
            </Button>
          </Upload>
        </>
      ),
    },
  ];

  const handleShelf = async (record: any) => {
    const res = await updateBookStatusById({
      bookId: record.bookId,
      status: record.status == 0 ? 1 : 0,
    });

    if (res.success) {
      message.success("图书已上架");
      getData();
    }
  };

  const handleUnshelf = async (record: any) => {
    const res = await updateBookStatusById({
      bookId: record.bookId,
      status: record.status == 0 ? 1 : 0,
    });

    if (res.success) {
      message.success("成功取消上架");
      getData();
    }
  };

  const handleClassfiy = async (record: any) => {
    const res = await updateBookTypeById({
      bookId: selectedBook?.bookId,
      typeId: record.category,
    });

    if (res.success) {
      setShowClassfiy(false);
      getData();
      message.success("成功修改分类");
    }
  };

  const onFinish = async (values: any) => {
    const newBook = {
      ...values,
      publishDate: values.publishDate.format("YYYY-MM-DD"),
      key: books.length,
      isShelved: false, // 初始状态为未上架
      pdfFile: null, // 初始状态为未上传PDF文件
    };

    // 请求数据库保存

    const res = await saveBookByForm(parseBookData(newBook));
    // setBooks([...books, newBook]);

    // 成功后提示
    if (res.success) {
      form.resetFields();
      setIsModalVisible(false);
      getData();
      message.success("图书信息已录入");
    }
  };

  const handlePdfUpload = async (file: any, record: any) => {
    const res = await uploadExcelFile(file);
    if (typeof res == 'string') {
      // 保存到数据库中
      const resulte = await updateBookFileUrlById({
        bookId: record?.bookId,
        fileUrl: res,
      });
      getData();
      message.success("图书上传成功");
    }
    return false; // 阻止默认的上传行为
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleSearch = async (e: any) => {
    const res: any = await searchBookByName({
      name: e,
      page: 0,
      size: 10,
    });

    setBooks(res?.data?.content);
    setPageContent({...pageContent,totalElements: res?.data?.content?.length})
  };

  const handleCategoryModalCancel = () => {
    setShowClassfiy(false);
  };
  const handleUpdateClassfiy = () => {
    const formClass = formClassfiy.getFieldsValue();
    handleClassfiy(formClass);
  };

  const handleUploadSuccess = async () => {
    getData();
    setShowUpload(false);
  };

  const parseDataSource = (list: any[]) => {
    return list?.map((item) => ({
      ...item,
    }));
  };
  const parseBookData = (data: any) => {
    return {
      ...data,
    };
  };

  const getData = async (page = 0) => {
    const res: any = await getBooksByPage({ page: page, size: 10 });
    const resultList = res?.data?.content ?? [];
    setShowUpload(false);
    setBooks(parseDataSource(resultList));
    setPageContent(res.data)
  };

  const handleTableChange = (pagination: any) => {
    setCurrentPage(pagination.current);
    getData(Number(pagination?.current) - 1); // 后端页码从0开始，前端从1开始
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <div style={{ padding: "20px" }}>
      <Search
        placeholder="搜索书名"
        onSearch={handleSearch}
        style={{ marginBottom: 16, width: 300, marginRight: 16 }}
      />
      <Button
        type="primary"
        onClick={showModal}
        style={{ marginBottom: "20px" }}
      >
        单条录入
      </Button>
      <Button
        icon={<UploadOutlined />}
        style={{ marginLeft: 15 }}
        onClick={() => setShowUpload(true)}
      >
        批量上传
      </Button>
      <Modal
        title="选择分类"
        open={showClassfiy}
        onCancel={handleCategoryModalCancel}
        onOk={handleUpdateClassfiy}
        okText="确认"
        cancelText="取消"
      >
        <Form form={formClassfiy} layout="vertical">
          <Item
            name="category"
            label="分类"
            rules={[{ required: true, message: "请选择分类" }]}
          >
            <Select placeholder="选择分类" style={{ width: "100%" }}>
              {categories.map((category) => (
                <Option key={category.key} value={category.key}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Item>
        </Form>
      </Modal>
      <Modal
        title="添加图书"
        open={isModalVisible}
        footer={null}
        onCancel={handleCancel}
      >
        <Form form={form} onFinish={onFinish} layout="vertical">
          <Item
            name="name"
            label="书名"
            rules={[{ required: true, message: "请输入书名" }]}
          >
            <Input />
          </Item>
          <Item
            name="author"
            label="作者"
            rules={[{ required: true, message: "请输入作者" }]}
          >
            <Input />
          </Item>
          <Item
            name="isbn"
            label="ISBN"
            rules={[{ required: true, message: "请输入ISBN" }]}
          >
            <Input />
          </Item>
          <Item
            name="publishDate"
            label="出版日期"
            rules={[{ required: true, message: "请选择出版日期" }]}
          >
            <DatePicker />
          </Item>
          <Item
            name="typeId"
            label="图书分类"
            rules={[{ required: true, message: "请选择图书分类" }]}
          >
            <Select>
              {categories.map((category) => (
                <Select.Option value={category.key}>
                  {category.name}
                </Select.Option>
              ))}
            </Select>
          </Item>
          <Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Item>
        </Form>
      </Modal>
      {/* <Upload
        beforeUpload={handleUpload}
        showUploadList={false}
        accept=".xlsx, .xls"
      >
        <Button icon={<UploadOutlined />} style={{ marginLeft: 15 }}>批量上传</Button>
      </Upload> */}
      <Table
        columns={columns}
        dataSource={books}
        style={{ marginTop: "20px" }}
        onChange={handleTableChange}
        pagination={{ pageSize: 10, total: pageContent?.totalElements ?? 0, showSizeChanger: false, current: currentPage }}
      />

      <UploadModal
        title="批量上传"
        open={showUpload}
        onClose={handleUploadSuccess}
        onCancel={handleUploadSuccess}
        onOk={handleUploadSuccess}
        okText="确认"
        cancelText="取消"
      />

      {/* <UploadModal
        title="上传图书"
        open={showPdfUpload}
        onClose={handleUploadSuccess}
        onCancel={handleUploadSuccess}
        onOk={handleUploadSuccess}
        okText="确认"
        cancelText="取消"
      /> */}
    </div>
  );
};

export default Creat;
